<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SPI 智能查询助手</title>
    <!-- 引入 ECharts - 使用国内CDN -->
    <script src="https://registry.npmmirror.com/echarts/5.4.3/files/dist/echarts.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB',
                         'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            width: 95%;
            max-width: 900px;
            height: 90vh;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 24px;
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-icon {
            width: 32px;
            height: 32px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
            background: #f7f7f8;
        }

        .message {
            margin-bottom: 16px;
            display: flex;
            gap: 12px;
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            font-weight: 600;
        }

        .message.user .avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .message.assistant .avatar {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 12px;
            line-height: 1.6;
            word-wrap: break-word;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.assistant .message-content {
            background: white;
            color: #374151;
            border-bottom-left-radius: 4px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        }

        .data-table {
            margin-top: 12px;
            overflow-x: auto;
            border-radius: 8px;
            background: #f9fafb;
        }

        .data-table table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }

        .data-table th {
            background: #f3f4f6;
            padding: 10px 12px;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 2px solid #e5e7eb;
        }

        .data-table td {
            padding: 10px 12px;
            border-bottom: 1px solid #e5e7eb;
            color: #6b7280;
        }

        .data-table tr:last-child td {
            border-bottom: none;
        }

        .data-table tr:hover {
            background: #f9fafb;
        }

        .loading {
            display: flex;
            gap: 4px;
            padding: 8px 0;
        }

        .loading span {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #9ca3af;
            animation: bounce 1.4s infinite ease-in-out both;
        }

        .loading span:nth-child(1) { animation-delay: -0.32s; }
        .loading span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes bounce {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }

        .input-container {
            padding: 20px 24px;
            background: white;
            border-top: 1px solid #e5e7eb;
        }

        .input-wrapper {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        .input-box {
            flex: 1;
            position: relative;
        }

        #userInput {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            font-size: 15px;
            resize: none;
            outline: none;
            transition: all 0.2s;
            font-family: inherit;
            max-height: 120px;
        }

        #userInput:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        #sendBtn {
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }

        #sendBtn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        #sendBtn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .quick-questions {
            display: flex;
            gap: 8px;
            margin-bottom: 12px;
            flex-wrap: wrap;
        }

        .quick-question {
            padding: 8px 14px;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 20px;
            font-size: 13px;
            color: #6b7280;
            cursor: pointer;
            transition: all 0.2s;
        }

        .quick-question:hover {
            background: #f3f4f6;
            border-color: #667eea;
            color: #667eea;
        }

        .metadata {
            font-size: 12px;
            color: #9ca3af;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid #f3f4f6;
        }

        /* 导出按钮样式 */
        .export-buttons {
            margin-top: 12px;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .export-btn {
            padding: 8px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .export-message {
            margin-top: 8px;
            padding: 10px 12px;
            background: #eff6ff;
            border-left: 3px solid #3b82f6;
            border-radius: 6px;
            font-size: 13px;
            color: #1e40af;
        }

        /* ECharts 图表容器 */
        .chart-container {
            margin-top: 16px;
            width: 100%;
            height: 350px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        @media (max-width: 768px) {
            .container {
                width: 100%;
                height: 100vh;
                border-radius: 0;
            }

            .message-content {
                max-width: 85%;
            }

            .data-table {
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-icon">🤖</div>
            <div>SPI 智能查询助手</div>
        </div>

        <div class="chat-container" id="chatContainer">
            <div class="message assistant">
                <div class="avatar">AI</div>
                <div class="message-content">
                    您好！我是 SPI 智能查询助手。您可以用自然语言向我提问，我会帮您查询数据库信息。
                    <div style="margin-top: 12px; font-size: 14px; opacity: 0.8;">
                        试试问我：<br>
                        • 查询当前在校的外来车辆<br>
                        • 统计反复进出宿舍超过5次的学生<br>
                        • 查询十月份图书馆进出情况<br>
                        • 查看设备统计信息<br>
                        • 查询最近的告警记录
                    </div>
                </div>
            </div>
        </div>

        <div class="input-container">
            <div class="quick-questions">
                <div class="quick-question" onclick="sendQuickQuestion('查询当前在校的外来车辆')">
                    查询外来车辆
                </div>
                <div class="quick-question" onclick="sendQuickQuestion('统计反复进出宿舍超过5次的学生')">
                    宿舍进出统计
                </div>
                <div class="quick-question" onclick="sendQuickQuestion('查询十月份图书馆进出情况')">
                    图书馆进出
                </div>
                <div class="quick-question" onclick="sendQuickQuestion('查看设备统计信息')">
                    设备统计
                </div>
                <div class="quick-question" onclick="sendQuickQuestion('查询最近的告警记录')">
                    告警记录
                </div>
            </div>
            <div class="input-wrapper">
                <div class="input-box">
                    <textarea id="userInput" placeholder="输入您的问题..." rows="1"></textarea>
                </div>
                <button id="sendBtn" onclick="sendMessage()">发送</button>
            </div>
        </div>
    </div>

    <script>
        // 自动检测 API URL，支持不同端口
        const API_URL = window.location.origin + '/api/agent/query';
        let sessionId = 'session-' + Date.now();

        console.log('🌐 API URL:', API_URL);
        console.log('📍 Current location:', window.location.href);
        console.log('🖥️ Origin:', window.location.origin);
        
        // 测试服务器连通性
        fetch(window.location.origin + '/api/health')
            .then(response => {
                console.log('✅ Health check:', response.status);
                return response.text();
            })
            .then(data => console.log('Health response:', data))
            .catch(error => console.error('❌ Health check failed:', error));

        // 自动调整输入框高度
        const textarea = document.getElementById('userInput');
        textarea.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });

        // 支持回车发送
        textarea.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        function sendQuickQuestion(question) {
            document.getElementById('userInput').value = question;
            sendMessage();
        }

        async function sendMessage() {
            const input = document.getElementById('userInput');
            const message = input.value.trim();

            if (!message) return;

            // 禁用发送按钮
            const sendBtn = document.getElementById('sendBtn');
            sendBtn.disabled = true;

            // 清空输入框并重置高度
            input.value = '';
            input.style.height = 'auto';

            // 显示用户消息
            addMessage('user', message);

            // 显示加载状态
            const loadingId = addMessage('assistant', '<div class="loading"><span></span><span></span><span></span></div>');

            try {
                const requestBody = {
                    query: message,
                    sessionId: sessionId,
                    context: null,
                    databaseName: 'Test'
                };

                console.log('📤 发送请求到:', API_URL);
                console.log('📦 请求内容:', requestBody);

                const response = await fetch(API_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });

                console.log('📥 响应状态:', response.status);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('❌ 错误响应:', errorText);
                    console.error('❌ 响应头:', [...response.headers.entries()]);
                }

                // 错误处理已在上面添加，这里直接抛出
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }

                const data = await response.json();
                console.log('Response data:', data);

                // 移除加载状态
                document.getElementById(loadingId).remove();

                // 显示助手回复
                let content = data.summary || '查询完成';

                // 如果有数据，显示表格
                if (data.data && data.data.rows && data.data.rows.length > 0) {
                    content += renderTable(data.data);
                }

                // 添加导出链接（如果有）
                if (data.metadata && data.metadata.exportLinks) {
                    content += renderExportButtons(data.metadata.exportLinks, data.metadata.usedTools);
                }

                // 添加图表（如果有）
                console.log('🎨 检查图表配置:', data.metadata?.chartConfig);
                if (data.metadata && data.metadata.chartConfig) {
                    console.log('📊 图表类型:', data.metadata.chartConfig.type);
                    console.log('📊 图表配置:', data.metadata.chartConfig.config);
                    
                    if (data.metadata.chartConfig.type !== 'none') {
                        const chartId = 'chart-' + Date.now();
                        content += `<div id="${chartId}" class="chart-container"></div>`;
                        
                        console.log('✅ 创建图表容器:', chartId);
                        
                        // 延迟渲染图表，等待 DOM 加载
                        setTimeout(() => renderChart(chartId, data.metadata.chartConfig), 100);
                    } else {
                        console.log('⚠️ 图表类型为 none，不渲染');
                    }
                } else {
                    console.log('❌ 没有图表配置数据');
                }

                // 添加元数据
                if (data.metadata) {
                    content += `<div class="metadata">
                        ⏱️ 查询耗时: ${data.metadata.executionTimeMs}ms
                        ${data.metadata.rowCount !== null ? ` | 📊 返回记录: ${data.metadata.rowCount}条` : ''}
                    </div>`;
                }

                addMessage('assistant', content);

            } catch (error) {
                document.getElementById(loadingId).remove();
                addMessage('assistant', '❌ 抱歉，查询出错了：' + error.message);
            } finally {
                sendBtn.disabled = false;
                input.focus();
            }
        }

        function addMessage(role, content) {
            const chatContainer = document.getElementById('chatContainer');
            const messageDiv = document.createElement('div');
            const messageId = 'msg-' + Date.now() + Math.random();
            messageDiv.id = messageId;
            messageDiv.className = `message ${role}`;

            const avatar = role === 'user' ? '👤' : 'AI';

            messageDiv.innerHTML = `
                <div class="avatar">${avatar}</div>
                <div class="message-content">${content}</div>
            `;

            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;

            return messageId;
        }

        function renderTable(data) {
            if (!data.columns || !data.rows) return '';

            const totalRows = data.rows.length;
            const maxDisplayRows = 20;
            const displayRows = data.rows.slice(0, maxDisplayRows);
            const hasMore = totalRows > maxDisplayRows;

            let html = '<div class="data-table"><table>';

            // 表头
            html += '<tr>';
            data.columns.forEach(col => {
                html += `<th>${escapeHtml(col)}</th>`;
            });
            html += '</tr>';

            // 数据行（限制显示）
            displayRows.forEach(row => {
                html += '<tr>';
                data.columns.forEach(col => {
                    let value = row[col];
                    if (value === null || value === undefined) {
                        value = '-';
                    } else if (typeof value === 'string' && value.includes('T')) {
                        // 格式化日期时间
                        try {
                            const date = new Date(value);
                            value = date.toLocaleString('zh-CN');
                        } catch (e) {}
                    }
                    html += `<td>${escapeHtml(String(value))}</td>`;
                });
                html += '</tr>';
            });

            html += '</table>';
            
            // 如果数据超过20条，显示提示信息
            if (hasMore) {
                html += `<div style="text-align: center; padding: 12px; background: #fef3c7; border-top: 2px solid #f59e0b; color: #92400e; font-size: 13px; font-weight: 600;">
                    ⚠️ 仅显示前 ${maxDisplayRows} 条数据，共 ${totalRows} 条。完整数据请使用下方导出功能下载。
                </div>`;
            }
            
            html += '</div>';
            return html;
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        // 渲染导出按钮
        function renderExportButtons(exportLinks, usedTools) {
            const toolName = usedTools && usedTools.length > 0 ? usedTools[0] : '';
            
            let html = '<div class="export-buttons">';
            html += `<button class="export-btn" onclick='handleExport("${toolName}", "excel")'>
                        📊 导出 Excel
                     </button>`;
            html += `<button class="export-btn" onclick='handleExport("${toolName}", "csv")'>
                        📄 导出 CSV
                     </button>`;
            html += '</div>';
            
            if (exportLinks.message) {
                html += `<div class="export-message">${escapeHtml(exportLinks.message)}</div>`;
            }
            
            return html;
        }

        // 处理导出
        async function handleExport(toolName, format) {
            if (!toolName) {
                alert('无法确定导出的工具名称');
                return;
            }

            try {
                // 修正导出 URL
                const exportUrl = window.location.origin + '/api/export/tool';
                console.log('导出URL:', exportUrl);
                console.log('导出参数:', { toolName, format });

                const response = await fetch(exportUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        toolName: toolName,
                        parameters: {},
                        format: format,
                        fileName: `导出数据_${new Date().toISOString().split('T')[0]}`
                    })
                });

                if (!response.ok) {
                    throw new Error('导出失败：' + response.statusText);
                }

                // 下载文件
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `导出数据_${Date.now()}.${format === 'excel' ? 'xlsx' : 'csv'}`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                console.log('导出成功');
            } catch (error) {
                console.error('导出失败:', error);
                alert('导出失败：' + error.message);
            }
        }

        // 渲染 ECharts 图表
        function renderChart(chartId, chartConfig) {
            try {
                const chartDom = document.getElementById(chartId);
                if (!chartDom) {
                    console.error('找不到图表容器:', chartId);
                    return;
                }

                const myChart = echarts.init(chartDom);
                const config = JSON.parse(chartConfig.config);
                
                console.log('渲染图表:', chartConfig.type, config);
                
                myChart.setOption(config);

                // 响应式调整
                window.addEventListener('resize', () => {
                    myChart.resize();
                });
            } catch (error) {
                console.error('图表渲染失败:', error);
            }
        }

        // 页面加载完成后聚焦输入框
        window.onload = () => {
            document.getElementById('userInput').focus();
        };
    </script>
</body>
</html>
